package com.dj.mingkong.portal.biz.service.music.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.common.constant.RedisConstants;
import com.dj.mingkong.common.infrastructure.eo.database.music.MusicEo;
import com.dj.mingkong.common.infrastructure.eo.database.music.MusicVisitEo;
import com.dj.mingkong.common.microservice.UserContext;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.portal.biz.controller.music.vo.request.MusicVisitAddVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.MusicVisitCancelVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.MusicVisitQueryVo;
import com.dj.mingkong.portal.biz.controller.music.vo.response.MusicVisitVo;
import com.dj.mingkong.portal.biz.core.base.context.UserContextHolder;
import com.dj.mingkong.portal.biz.repository.database.music.MusicRepository;
import com.dj.mingkong.portal.biz.repository.database.music.MusicVisitRepository;
import com.dj.mingkong.portal.biz.service.music.MusicVisitService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.SecureRandom;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 音乐访客服务实现
 *
 * @author zenglonghui
 * @date: 2022/8/23 11:01
 */
@Slf4j
@Service("musicVisitService")
public class MusicVisitServiceImpl implements MusicVisitService {
    @Resource
    private MusicVisitRepository musicVisitRepository;
    @Resource
    private MusicRepository musicRepository;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserContextHolder userContextHolder;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(MusicVisitAddVo addVo) {
        final MusicEo musicEo = musicRepository.getById(addVo.getMusicId());
        AssertUtils.isNotNull(musicEo, "musicId invalid");
        //添加人气
        addPopularity(addVo);
        userContextHolder.getCurrentUserOpt().ifPresent(userInfoContext -> {
            final String key = RedisConstants.VISIT_MUSIC
                    .concat(userInfoContext.getId().toString())
                    .concat(RedisConstants.KEY_SPLIT)
                    .concat(addVo.getMusicId().toString());
            if (Boolean.FALSE.equals(redisTemplate.hasKey(key))) {
                saveMusicVisit(key, userInfoContext.getId(), musicEo);
            }
        });
    }

    @Override
    public Page<MusicVisitVo> pageByVo(MusicVisitQueryVo queryVo) {
        return musicVisitRepository.getMapper().listPage(Page.of(queryVo.getPage(), queryVo.getPageSize()), queryVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancel(MusicVisitCancelVo cancelVo) {
        final MusicEo musicEo = musicRepository.getById(cancelVo.getMusicId());
        AssertUtils.isNotNull(musicEo, "musicEo invalid");
        final Optional<MusicVisitEo> optional = musicVisitRepository
                .oneOptByUserIdAndMusicId(UserContext.getUserId(), cancelVo.getMusicId());
        optional.ifPresent(musicVisitEo -> {
            musicVisitRepository.deleteById(musicVisitEo.getId());
            musicRepository.updateById(musicEo.setVisitCount(musicEo.getVisitCount() - 1));
        });
    }

    private void saveMusicVisit(String key, Long userId, MusicEo musicEo) {
        final Optional<MusicVisitEo> eoOptional = musicVisitRepository.oneOptByUserIdAndMusicId(userId, musicEo.getId());
        eoOptional.ifPresentOrElse(musicVisitEo -> {
            log.info("更新访客信息 userId:{}, musicId:{}", userId, musicEo.getId());
            musicVisitRepository.updateById(musicVisitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_MUSIC, 5, TimeUnit.MINUTES);
        }, () -> {
            log.info("保存访客信息 userId:{}, musicId:{}", userId, musicEo.getId());
            final MusicVisitEo visitEo = MusicVisitEo.builder().userId(userId)
                    .musicId(musicEo.getId()).build();
            musicVisitRepository.save(visitEo);
            redisTemplate.opsForValue().set(key, RedisConstants.VISIT_MUSIC, 5, TimeUnit.MINUTES);
            musicRepository.updateById(musicEo.setVisitCount(musicEo.getVisitCount() + 1));
        });
    }

    private void addPopularity(MusicVisitAddVo addVo) {
        final var rand = new SecureRandom();
        final long num = rand.nextLong(100) + 1;
        final Long increment = redisTemplate.boundHashOps(RedisConstants.POPULARITY_MUSIC)
                .increment(addVo.getMusicId(), num);
        log.info("添加音乐人气 id :{}, 点击数： {}", addVo.getMusicId(), increment);
    }
}
